-- seckill.lua
local voucherId = ARGV[1]
local userId = ARGV[2]
local orderId = ARGV[3]

-- 库存key
local stockKey = 'seckill:stock:' .. voucherId
-- 订单key
local orderKey = 'seckill:order:' .. voucherId

-- 3. 执行业务
-- 3.1 判断库存
if tonumber(redis.call('get', stockKey))  <= 0 then
    return 1
end
-- 3.2 判断用户一人一单 SISMEMBER orderKey userId
if redis.call('sismember', orderKey, userId) == 1 then
    return 2
end
-- 3.3 扣库存
redis.call('incrby',stockKey,-1)
-- 3.4 下单
redis.call('sadd',orderKey,userId)
-- 3.5 发送消息到队列 XADD stream.orders * k1 v1 k2 v2
redis.call('xadd','stream.orders','*','userId',userId,'voucherId',voucherId,'id',orderId)

return 0
